package com.xjrsoft.common.config;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.context.model.SaRequest;
import cn.dev33.satoken.exception.DisableLoginException;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import cn.dev33.satoken.filter.SaServletFilter;
import cn.dev33.satoken.interceptor.SaAnnotationInterceptor;
import cn.dev33.satoken.router.SaHttpMethod;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.util.StrUtil;
import com.xjrsoft.common.interceptor.XjrSaAnnotationInterceptor;
import com.xjrsoft.common.result.ResultCode;
import com.xjrsoft.common.utils.HttpContextUtils;
import com.xjrsoft.common.utils.RedisUtil;
import com.xjrsoft.core.constant.RedisKeyConstants;
import com.xjrsoft.module.buildCode.props.GlobalConfigProperties;
import io.lettuce.core.RedisURI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Locale;

/**
 * @Author: tzx
 * @Date:2022/3/3 17:18
 */
@Configuration
public class SaTokenConfig implements WebMvcConfigurer {

    @Autowired
    private GlobalConfigProperties globalConfigProperties;

    /**
     *  注册Sa-Token的注解拦截器，打开注解式鉴权功能
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册注解拦截器，并排除不需要注解鉴权的接口地址 (与登录拦截器无关)
        registry.addInterceptor(new XjrSaAnnotationInterceptor()).addPathPatterns("/**");
    }

    /**
     * 注册 [Sa-Token全局过滤器]
     */
    @Bean
    public SaServletFilter getSaServletFilter() {
        return new SaServletFilter()
                // 指定 拦截路由 与 放行路由
                .addInclude("/**")
                .setExcludeList(globalConfigProperties.getExcludeUrls())
                .addExclude("/favicon.ico")
                .addExclude("/webjars/**")
                .addExclude("/swagger-resources/**")
                .addExclude("/v2/api-docs")
                .addExclude("/druid/**")
                .addExclude("/swagger-ui.html")
                .addExclude("/login")
                .addExclude("/login/wechat")
                .addExclude("/login/logout")
                // 认证函数: 每次请求执行
                .setAuth(obj -> {

                    List<String> whiteList = globalConfigProperties.getWhiteList();

                    HttpServletRequest httpServletRequest = HttpContextUtils.getHttpServletRequest();

                    String remoteHost = httpServletRequest.getRemoteHost();

                    if(whiteList.contains(remoteHost)){
                        return;
                    }

                    // 登录认证 -- 拦截所有路由，并排除/user/doLogin 用于开放登录
                    SaRouter.match("/**", "/login", StpUtil::checkLogin);
                    // 更多拦截处理方式，请参考“路由拦截式鉴权”章节
                })

                // 异常处理函数：每次认证函数发生异常时执行此函数
                .setError(e -> {
                    if (e instanceof NotLoginException) {	// 如果是未登录异常3
                        return SaResult.get(ResultCode.UN_AUTHORIZED.getCode(),ResultCode.UN_AUTHORIZED.getMessage(),null);
                    } else if(e instanceof NotRoleException) {		// 如果是角色异常
                        return SaResult.get(ResultCode.REQ_REJECT.getCode(),ResultCode.REQ_REJECT.getMessage(),null);
                    } else if(e instanceof NotPermissionException) {	// 如果是权限异常
                        return SaResult.get(ResultCode.REQ_REJECT.getCode(),ResultCode.REQ_REJECT.getMessage(),null);
                    } else if(e instanceof DisableLoginException) {	// 如果是被封禁异常
                        return SaResult.get(ResultCode.REQ_REJECT.getCode(),ResultCode.REQ_REJECT.getMessage(),null);
                    } else {	// 普通异常, 输出：500 + 异常信息
                        return SaResult.get(ResultCode.INTERNAL_SERVER_ERROR.getCode(),ResultCode.INTERNAL_SERVER_ERROR.getMessage(),null);
                    }
                })

                // 前置函数：在每次认证函数之前执行
                .setBeforeAuth(r -> {
                    // ---------- 设置一些安全响应头 ----------
                    SaHolder.getResponse()
                            // 服务器名称
                            .setServer("sa-server")
                            // 是否可以在iframe显示视图： DENY=不可以 | SAMEORIGIN=同域下可以 | ALLOW-FROM uri=指定域名下可以
                            .setHeader("X-Frame-Options", "SAMEORIGIN")
                            // 是否启用浏览器默认XSS防护： 0=禁用 | 1=启用 | 1; mode=block 启用, 并在检查到XSS攻击时，停止渲染页面
                            .setHeader("X-XSS-Protection", "1; mode=block")
                            // 禁用浏览器内容嗅探
                            .setHeader("X-Content-Type-Options", "nosniff")
                            .setHeader("Access-Control-Allow-Origin","*")
                            .setHeader("Access-Control-Allow-Methods","POST,GET,OPTIONS,DELETE,PUT")
                            .setHeader("Access-Control-Max-Age","3600")
                            .setHeader("Access-Control-Allow-Headers","*");

                    SaRouter.match(SaHttpMethod.OPTIONS).back();
                });
    }

}